﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NMoq.Core
{
    // Mock like 
    // Mock(Expression<Func<T,TResult>,Func<T,TResult>))
    public class DelegateDataProvider:IDataProvider 
    {
        private Dictionary<int, Delegate> MethodReturnCache
        {
            get;
            set;
        }

        public DelegateDataProvider()
        {
            MethodReturnCache = new Dictionary<int , Delegate>();
        }


        #region IDataProvider Members

        public void Write(MethodMessageInfo methodMessageInfo, object retValue)
        {
            Delegate implValue = retValue as Delegate ;
            if (implValue == null || implValue.IsEquivalent(methodMessageInfo.MethodInfo))
                throw new InvalidOperationException("parameter:retValue is not a delegate!");

            int methodHashcode = IdentifierFactory.GetIndentifier<IDataProvider>(methodMessageInfo);
            bool exists = MethodReturnCache.Keys.Contains(methodHashcode);
            if (exists)
                MethodReturnCache.Remove(methodHashcode);

            MethodReturnCache.Add(methodHashcode, implValue); 
        }

        public DataProviderResult Read(MethodMessageInfo methodMessageInfo)
        {
            DataProviderResult result = new DataProviderResult();

            int methodHashcode = IdentifierFactory.GetIndentifier<IDataProvider>(methodMessageInfo);
            bool exists = MethodReturnCache.Keys.Contains(methodHashcode); 
            result.HasValue = exists ;
            result.ReturnValue =exists ? MethodReturnCache[methodHashcode]:null ; 
            return result;
        }

        #endregion
    }
}
